import React, { useContext, useEffect, useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  FlatList,
  Alert,
  TextInput,
  Keyboard,
} from "react-native";
import TestQuesContext from "../../context/preparation/TestQuesContext";
import TestQuesCard from "../../components/preAdmin/TestQuesCard";
import TestContext from "../../context/preparation/TestContext";
import LoadingBar from "../../components/InterView/LoadingBar";

const AddTest = ({ navigation }) => {
  const { testQuesLists } = useContext(TestQuesContext);
  const { addTest, isTestLoading } = useContext(TestContext);
  const [keyboardIsOpen, setKeyboardIsOpen] = useState(false); //键盘
  const [title, setTitle] = useState(null);
  const [customList, setCustomList] = useState([]);
  const [choosedList, setChoosedList] = useState([]);

  useEffect(() => {
    let isMounted = true;
    if (isMounted) {
      if (testQuesLists) {
        let newQueationsNow = testQuesLists;
        newQueationsNow.map((item) => {
          item.checked = false;
        });
        setCustomList(newQueationsNow);
      }
    }

    return () => {
      isMounted = false;
    };
  }, []);

  useEffect(() => {
    Keyboard.addListener("keyboardDidShow", _keyboardDidShow);
    Keyboard.addListener("keyboardDidHide", _keyboardDidHide);

    // cleanup function
    return () => {
      Keyboard.removeAllListeners("keyboardDidShow");
      Keyboard.removeAllListeners("keyboardDidHide");
    };
  }, []);

  const _keyboardDidShow = () => {
    setKeyboardIsOpen(true);
  };

  const _keyboardDidHide = () => {
    setKeyboardIsOpen(false);
  };

  const onPressItem = (_id) => {
    let customListNow = [...customList];

    for (const item in customListNow) {
      if (customListNow[item]._id === _id) {
        if (customListNow[item].checked === false) {
          customListNow[item].checked = true;
          let itemChoosed = customListNow[item];

          setChoosedList([...choosedList, itemChoosed]);
        } else {
          customListNow[item].checked = false;
          let choosedListNow = choosedList.filter((item) => item._id !== _id);

          setChoosedList(choosedListNow);
        }
      }
    }
    setCustomList(customListNow);
  };

  const onConfirm = () => {
    let now = new Date();
    let mytime =
      now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate();
    Alert.alert("提示", "确定要提交吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: async () => {
          let item = {
            title: title,
            questions: choosedList,
            type: "unpublish",
            time: mytime,
          };
          addTest(item, () => {
            navigation.navigate("TestManage");
          });
        },
      },
    ]);
  };

  return (
    <View style={styles.container}>
      <LoadingBar visible={isTestLoading} />
      <FlatList
        ListHeaderComponent={
          <View style={styles.top}>
            <View style={styles.title}>
              <Text style={styles.titleIcon}>* </Text>
              <Text style={styles.titleText}>标题</Text>
            </View>
            <TextInput
              style={styles.inputBox}
              multiline={true}
              value={title}
              placeholder="请输入试卷标题"
              onChangeText={(text) => {
                setTitle(text);
              }}
            />
          </View>
        }
        data={customList}
        keyExtractor={(item, index) => {
          return index.toString();
        }}
        renderItem={({ item, index }) => (
          <TestQuesCard
            index={index}
            item={item}
            isAdd={true}
            onPressItem={onPressItem}
          />
        )}
      />
      {!keyboardIsOpen && (
        <View style={styles.buttonGroup}>
          <TouchableOpacity
            style={styles.cancelButton}
            onPress={() => navigation.goBack()}
          >
            <Text style={styles.cancelText}>取消</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.confirmButton}
            onPress={() => onConfirm()}
          >
            <Text style={styles.confirmText}>提交</Text>
          </TouchableOpacity>
        </View>
      )}
    </View>
  );
};

var styles = StyleSheet.create({
  container: {
    height: "100%",
    backgroundColor: "#f5f5f5",
    // padding: 10,
  },
  buttonGroup: {
    flexDirection: "row",
    justifyContent: "space-around",
    padding: 5,
  },
  confirmButton: {
    flex: 2,
    borderRadius: 5,
    margin: 10,
    padding: 10,
    backgroundColor: "#3ABEF0",
    alignItems: "center",
    justifyContent: "center",
    elevation: 2, //设置阴影角度，通过这个设置有无阴影
    shadowColor: "gray", // 设置阴影色
  },
  confirmText: {
    fontSize: 16,
    color: "#fff",
    fontWeight: "bold",
  },
  cancelButton: {
    flex: 1,
    borderRadius: 5,
    margin: 10,
    padding: 10,
    borderColor: "#3ABEF0",
    borderWidth: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  cancelText: {
    fontSize: 16,
    color: "#3ABEF0",
    fontWeight: "bold",
  },
  top: {
    margin: 13,
    marginBottom: 5,
    backgroundColor: "#fff",
    padding: 10,
  },
  title: {
    flexDirection: "row",
    marginBottom: 10,
  },
  titleIcon: { color: "red", fontSize: 16 },
  titleText: { color: "#555", fontSize: 16 },
  inputBox: {
    borderColor: "#ddd",
    borderWidth: 1,

    borderRadius: 2,
    padding: 10,
  },
});

export default AddTest;
